Mobile Apps
for iOS, Android, and Windows
Creating
with Xamarin.Forms
Cross-platform C# programming
CHARLES PETZOLD
PUBLISHED BY
Microsoft Press
A Division of Microsoft Corporation
One Microsoft Way
Redmond, Washington 98052-6399
Copyright © 2016 Xamarin, Inc.
All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any
means without the written permission of the publisher.
ISBN: 978-1-5093-0297-0
Printed and bound in the United States of America.
First Printing
Microsoft Press books are available through booksellers and distributors worldwide. If you need support related to
this book, email Microsoft Press Support at mspinput@microsoft.com. Please tell us what you think of this book at
http://aka.ms/tellpress.
This book is provided “as-is” and expresses the author’s views and opinions. The views, opinions and information
expressed in this book, including URL and other Internet website references, may change without notice.
Some examples depicted herein are provided for illustration only and are fictitious. No real association or connec-
tion is intended or should be inferred.
Microsoft and the trademarks listed at http://www.microsoft.com on the “Trademarks” webpage are trademarks of
the Microsoft group of companies. All other marks are property of their respective owners.
Acquisitions and Project Editor: Devon Musgrave
Editorial production: John Pierce, Flying Squirrel Press
Cover illustration: Serena Zhang
Contents
Foreword.................................................................................................................................................................................................xv
Introduction.......................................................................................................................................................................................... xvi
Chapter 1
How does Xamarin.Forms fit in?..............................................................................................1
Cross-platform mobile development...................................................................................................................................... 2
The mobile landscape............................................................................................................................................................... 2
Problem 1: Different user-interface paradigms.............................................................................................................. 2
Problem 2: Different development environments......................................................................................................... 3
Problem 3: Different programming interfaces................................................................................................................ 3
Problem 4: Different programming languages.............................................................................................................. 3
The C# and .NET solution ............................................................................................................................................................ 4
A single language for all platforms..................................................................................................................................... 5
Sharing code................................................................................................................................................................................. 6
Introducing Xamarin.Forms......................................................................................................................................................... 8
The Xamarin.Forms option...................................................................................................................................................... 8
XAML support............................................................................................................................................................................13
Platform specificity...................................................................................................................................................................14
A cross-platform panacea?...................................................................................................................................................15
Your development environment.............................................................................................................................................15
Machines and IDEs...................................................................................................................................................................16
Devices and emulators ...........................................................................................................................................................16
Installation........................................................................................................................................................................................17
Creating an iOS app.................................................................................................................................................................17
Creating an Android app.......................................................................................................................................................18
Creating a Windows app .......................................................................................................................................................18
All ready?......................................................................................................................................................................................19
Contents
iv
Chapter 2
Anatomy of an app ................................................................................................................. 20
Say hello ............................................................................................................................................................................................20
Inside the files .................................................................................................................................................................................24
The iOS project...........................................................................................................................................................................26
The Android project.................................................................................................................................................................27
The Universal Windows Platform project........................................................................................................................28
Nothing special!.........................................................................................................................................................................28
PCL or SAP?......................................................................................................................................................................................29
Labels for text..................................................................................................................................................................................31
Solution 1. Include padding on the page .......................................................................................................................35
Solution 2. Include padding just for iOS (SAP only)....................................................................................................36
Solution 3. Include padding just for iOS (PCL or SAP)...............................................................................................37
Solution 4. Center the label within the page.................................................................................................................39
Solution 5. Center the text within the label....................................................................................................................41
Chapter 3
Deeper into text ...................................................................................................................... 42
Wrapping paragraphs..................................................................................................................................................................42
Text and background colors......................................................................................................................................................44
The Color structure .......................................................................................................................................................................46
Changing the application color scheme...............................................................................................................................50
Font sizes and attributes.............................................................................................................................................................51
Formatted text................................................................................................................................................................................53
Chapter 4
Scrolling the stack................................................................................................................... 60
Stacks of views ................................................................................................................................................................................60
Scrolling content............................................................................................................................................................................64
The Expands option......................................................................................................................................................................70
Frame and BoxView......................................................................................................................................................................74
A ScrollView in a StackLayout?.................................................................................................................................................82
Chapter 5
Dealing with sizes.................................................................................................................... 87
Pixels, points, dps, DIPs, and DIUs ...............................................................................................................................................87
Metrical sizes ...................................................................................................................................................................................96
Contents
v
Estimated font sizes......................................................................................................................................................................97
Fitting text to available size.......................................................................................................................................................99
A fit-to-size clock........................................................................................................................................................................ 103
Accessibility issues......................................................................................................................................................................105
Empirically fitting text............................................................................................................................................................... 108
Chapter 6
Button clicks...........................................................................................................................113
Processing the click........................................................................................................................................................................ 113
Sharing button clicks.................................................................................................................................................................116
Anonymous event handlers ................................................................................................................................................... 119
Distinguishing views with IDs................................................................................................................................................ 121
Saving transient data ................................................................................................................................................................ 124
Chapter 7
XAML vs. code........................................................................................................................131
Properties and attributes......................................................................................................................................................... 132
Property-element syntax......................................................................................................................................................... 136
Adding a XAML page to your project................................................................................................................................ 140
The XAML compiler...................................................................................................................................................................145
Platform specificity in the XAML file...................................................................................................................................146
The content property attribute............................................................................................................................................. 150
Formatted text............................................................................................................................................................................. 152
Chapter 8
Code and XAML in harmony ................................................................................................156
Passing arguments.....................................................................................................................................................................156
Constructors with arguments............................................................................................................................................ 156
Can I call methods from XAML?......................................................................................................................................159
The x:Name attribute................................................................................................................................................................ 161
Custom XAML-based views.................................................................................................................................................... 167
Events and handlers ..................................................................................................................................................................172
Tap gestures ................................................................................................................................................................................. 175
Chapter 9
Platform-specific API calls....................................................................................................182
Preprocessing in the Shared Asset Project....................................................................................................................... 182
Parallel classes and the Shared Asset Project.................................................................................................................. 185
Contents
vi
DependencyService and the Portable Class Library......................................................................................................187
Platform-specific sound generation....................................................................................................................................191
Chapter 10
XAML markup extensions..................................................................................................198
The code infrastructure............................................................................................................................................................198
Accessing static members .......................................................................................................................................................200
Resource dictionaries ................................................................................................................................................................206
StaticResource for most purposes...................................................................................................................................207
A tree of dictionaries ............................................................................................................................................................214
DynamicResource for special purposes.........................................................................................................................218
Lesser-used markup extensions............................................................................................................................................221
A custom markup extension...................................................................................................................................................222
Chapter 11
The bindable infrastructure...............................................................................................227
The Xamarin.Forms class hierarchy......................................................................................................................................228
A peek into BindableObject and BindableProperty......................................................................................................235
Defining bindable properties.................................................................................................................................................241
The read-only bindable property....................................................................................................................................246
Chapter 12
Styles.....................................................................................................................................252
The basic Style..............................................................................................................................................................................252
Styles in code................................................................................................................................................................................259
Style inheritance..........................................................................................................................................................................261
Implicit styles................................................................................................................................................................................265
Dynamic styles .............................................................................................................................................................................270
Device styles..................................................................................................................................................................................278
Chapter 13
Bitmaps.................................................................................................................................283
Platform-independent bitmaps ............................................................................................................................................284
Fit and fill...................................................................................................................................................................................287
Embedded resources............................................................................................................................................................289
More on sizing.........................................................................................................................................................................295
Browsing and waiting...........................................................................................................................................................307
Streaming bitmaps.....................................................................................................................................................................311
Contents
vii
Accessing the streams.......................................................................................................................................................... 311
Generating bitmaps at run time......................................................................................................................................314
Platform-specific bitmaps....................................................................................................................................................... 318
Bitmap resolutions.................................................................................................................................................................320
Device-independent bitmaps for iOS............................................................................................................................ 322
Device-independent bitmaps for Android .................................................................................................................. 322
Device-independent bitmaps for Windows Runtime platforms......................................................................... 323
Toolbars and their icons...................................................................................................................................................... 327
Icons for Android...................................................................................................................................................................329
Icons for Windows Runtime platforms.......................................................................................................................... 330
Icons for iOS devices ............................................................................................................................................................ 331
Button images......................................................................................................................................................................... 335
Chapter 14
Absolute layout....................................................................................................................338
AbsoluteLayout in code........................................................................................................................................................... 339
Attached bindable properties ............................................................................................................................................... 344
Proportional sizing and positioning ...................................................................................................................................348
Working with proportional coordinates ........................................................................................................................... 350
AbsoluteLayout and XAML..................................................................................................................................................... 355
Overlays.......................................................................................................................................................................................... 359
Some fun........................................................................................................................................................................................ 362
Chapter 15
The interactive interface.....................................................................................................371
View overview.............................................................................................................................................................................. 371
Slider and Stepper......................................................................................................................................................................372
Slider basics.............................................................................................................................................................................. 372
Common pitfalls.....................................................................................................................................................................375
Slider color selection ............................................................................................................................................................ 377
The Stepper difference........................................................................................................................................................ 382
Switch and CheckBox................................................................................................................................................................ 384
Switch basics............................................................................................................................................................................ 384
A traditional CheckBox........................................................................................................................................................ 387
Contents
viii
Typing text.....................................................................................................................................................................................392
Keyboard and focus..............................................................................................................................................................392
Choosing the keyboard.......................................................................................................................................................393
Entry properties and events...............................................................................................................................................396
The Editor difference............................................................................................................................................................402
The SearchBar..........................................................................................................................................................................405
Date and time selection...........................................................................................................................................................410
The DatePicker........................................................................................................................................................................410
The TimePicker (or is it a TimeSpanPicker?)................................................................................................................414
Chapter 16
Data binding........................................................................................................................418
Binding basics...............................................................................................................................................................................418
Code and XAML ..........................................................................................................................................................................420
Source and BindingContext....................................................................................................................................................423
The binding mode......................................................................................................................................................................430
String formatting ........................................................................................................................................................................437
Why is it called “Path”?.............................................................................................................................................................440
Binding value converters .........................................................................................................................................................443
Bindings and custom views.....................................................................................................................................................451
Chapter 17
Mastering the Grid..............................................................................................................458
The basic Grid...............................................................................................................................................................................458
The Grid in XAML...................................................................................................................................................................458
The Grid in code.....................................................................................................................................................................464
The Grid bar chart..................................................................................................................................................................467
Alignment in the Grid...........................................................................................................................................................471
Cell dividers and borders....................................................................................................................................................475
Almost real-life Grid examples..............................................................................................................................................481
Responding to orientation changes...............................................................................................................................484
Chapter 18
MVVM...................................................................................................................................491
MVVM interrelationships.........................................................................................................................................................491
ViewModels and data binding..............................................................................................................................................493
Contents
ix
A ViewModel clock................................................................................................................................................................ 494
Interactive properties in a ViewModel.......................................................................................................................... 500
A Color ViewModel............................................................................................................................................................... 507
Streamlining the ViewModel............................................................................................................................................. 513
The Command interface.......................................................................................................................................................... 517
Simple method executions ................................................................................................................................................ 519
A calculator, almost............................................................................................................................................................... 523
ViewModels and the application lifecycle........................................................................................................................ 531
Chapter 19
Collection views...................................................................................................................535
Program options with Picker ................................................................................................................................................. 536
The Picker and event handling......................................................................................................................................... 536
Data binding the Picker ...................................................................................................................................................... 540
Rendering data with ListView................................................................................................................................................ 543
Collections and selections.................................................................................................................................................. 544
The row separator..................................................................................................................................................................545
Data binding the selected item........................................................................................................................................ 547
The ObservableCollection difference............................................................................................................................. 551
Templates and cells............................................................................................................................................................... 553
Custom cells............................................................................................................................................................................. 561
Grouping the ListView items............................................................................................................................................. 565
Custom group headers........................................................................................................................................................ 569
ListView and interactivity.................................................................................................................................................... 570
ListView and MVVM..................................................................................................................................................................574
A collection of ViewModels............................................................................................................................................... 574
Selection and the binding context..................................................................................................................................586
Context menus........................................................................................................................................................................ 590
Varying the visuals.................................................................................................................................................................595
Refreshing the content........................................................................................................................................................ 597
The TableView and its intents................................................................................................................................................ 604
Properties and hierarchies.................................................................................................................................................. 604
Contents
x
A prosaic form.........................................................................................................................................................................606
Custom cells .............................................................................................................................................................................610
Conditional sections..............................................................................................................................................................616
A TableView menu.................................................................................................................................................................620
Chapter 20
Async and file I/O................................................................................................................624
From callbacks to await............................................................................................................................................................625
An alert with callbacks .........................................................................................................................................................626
An alert with lambdas ..........................................................................................................................................................630
An alert with await.................................................................................................................................................................630
An alert with nothing ...........................................................................................................................................................632
Saving program settings asynchronously.....................................................................................................................635
A platform-independent timer.........................................................................................................................................639
File input/output.........................................................................................................................................................................641
Good news and bad news..................................................................................................................................................641
A first shot at cross-platform file I/O .............................................................................................................................643
Accommodating Windows Runtime file I/O...............................................................................................................650
Platform-specific libraries........................................................................................................................................................651
Keeping it in the background...........................................................................................................................................662
Don’t block the UI thread!..................................................................................................................................................664
Your own awaitable methods................................................................................................................................................664
The basic Mandelbrot set ...................................................................................................................................................666
Marking progress...................................................................................................................................................................673
Cancelling the job..................................................................................................................................................................676
An MVVM Mandelbrot ........................................................................................................................................................680
Back to the web...........................................................................................................................................................................701
Chapter 21
Transforms...........................................................................................................................704
The translation transform........................................................................................................................................................705
Text effects................................................................................................................................................................................708
Jumps and animations.........................................................................................................................................................711
The scale transform....................................................................................................................................................................715
Contents
xi
Anchoring the scale.............................................................................................................................................................. 723
The rotation transform............................................................................................................................................................. 726
Rotated text effects............................................................................................................................................................... 727
An analog clock......................................................................................................................................................................734
Vertical sliders?.......................................................................................................................................................................742
3D-ish rotations........................................................................................................................................................................... 743
Chapter 22
Animation.............................................................................................................................748
Exploring basic animations..................................................................................................................................................... 748
Setting the animation duration........................................................................................................................................ 750
Relative animations............................................................................................................................................................... 751
Awaiting animations............................................................................................................................................................. 751
Composite animations......................................................................................................................................................... 754
Task.WhenAll and Task.WhenAny...................................................................................................................................756
Rotation and anchors........................................................................................................................................................... 756
Easing functions .....................................................................................................................................................................759
Your own easing functions ................................................................................................................................................ 763
Entrance animations............................................................................................................................................................. 773
Forever animations................................................................................................................................................................ 778
Animating the Bounds property......................................................................................................................................793
Your own awaitable animations.......................................................................................................................................805
Deeper into animation............................................................................................................................................................. 808
Sorting out the classes......................................................................................................................................................... 808
ViewExtensions class............................................................................................................................................................. 809
The Animation class.............................................................................................................................................................. 810
AnimationExtensions class ................................................................................................................................................. 811
Working with the Animation class..................................................................................................................................812
Child animations ....................................................................................................................................................................815
Beyond the high-level animation methods ................................................................................................................ 818
More of your own awaitable methods.......................................................................................................................... 819
Implementing a Bezier animation...................................................................................................................................823
Contents
xii
Working with AnimationExtensions ...............................................................................................................................828
Structuring your animations...................................................................................................................................................834
Chapter 23
Triggers and behaviors.......................................................................................................835
Triggers...........................................................................................................................................................................................836
The simplest trigger..............................................................................................................................................................836
Trigger actions and animations........................................................................................................................................841
More event triggers ..............................................................................................................................................................847
Data triggers ............................................................................................................................................................................853
Combining conditions in the MultiTrigger..................................................................................................................858
Behaviors........................................................................................................................................................................................868
Behaviors with properties...................................................................................................................................................871
Toggles and check boxes....................................................................................................................................................876
Responding to taps ...............................................................................................................................................................889
Radio buttons ..........................................................................................................................................................................893
Fades and orientation ..........................................................................................................................................................908
Chapter 24
Page navigation...................................................................................................................920
Modal pages and modeless pages......................................................................................................................................921
Animated page transitions.................................................................................................................................................930
Visual and functional variations.......................................................................................................................................931
Exploring the mechanics.....................................................................................................................................................937
Enforcing modality................................................................................................................................................................947
Navigation variations ................................................................................................................................................................955
Making a navigation menu................................................................................................................................................957
Manipulating the navigation stack.................................................................................................................................963
Dynamic page generation..................................................................................................................................................965
Patterns of data transfer ..........................................................................................................................................................969
Constructor arguments........................................................................................................................................................970
Properties and method calls..............................................................................................................................................974
The messaging center..........................................................................................................................................................981
Events..........................................................................................................................................................................................984
Contents
xiii
The App class intermediary ............................................................................................................................................... 987
Switching to a ViewModel................................................................................................................................................. 990
Saving and restoring page state......................................................................................................................................995
Saving and restoring the navigation stack....................................................................................................................... 999
Something like a real-life app ........................................................................................................................................1006
Chapter 25
Page varieties.................................................................................................................... 1020
Master and Detail.....................................................................................................................................................................1020
Exploring the behaviors ....................................................................................................................................................1021
Back to school.......................................................................................................................................................................1029
Your own user interface....................................................................................................................................................1034
TabbedPage................................................................................................................................................................................1042
Discrete tab pages...............................................................................................................................................................1043
Using an ItemTemplate.....................................................................................................................................................1050
Chapter 26
Custom layouts ................................................................................................................. 1054
An overview of layout.............................................................................................................................................................1054
Parents and children...........................................................................................................................................................1055
Sizing and positioning.......................................................................................................................................................1056
Constraints and size requests..........................................................................................................................................1060
Infinite constraints...............................................................................................................................................................1064
Peeking inside the process...............................................................................................................................................1066
Deriving from Layout..............................................................................................................................................1074
An easy example..................................................................................................................................................................1075
Vertical and horizontal positioning simplified.........................................................................................................1082
Invalidation.............................................................................................................................................................................1084
Some rules for coding layouts........................................................................................................................................1087
A layout with properties ...................................................................................................................................................1088
No unconstrained dimensions allowed!.....................................................................................................................1099
Overlapping children..........................................................................................................................................................1106
More attached bindable properties.............................................................................................................................1117
Layout and LayoutTo..........................................................................................................................................................1122
Contents
xiv
Chapter 27
Custom renderers..............................................................................................................1127
The complete class hierarchy.............................................................................................................................................. 1127
Hello, custom renderers!....................................................................................................................................................... 1130
Renderers and properties..................................................................................................................................................... 1135
Renderers and events............................................................................................................................................................. 1149
Foreword
The idea for producing a book on Xamarin.Forms is one we’ve had for almost as long as we’ve been
working on the product. Of course, we didn’t know it would be written by such a talented and highly
regarded author. We couldn’t have asked for a better-qualified person, nor someone who would re-
quire so little of us to get inside our minds! Charles offers insights in such beautiful and simple ways, as
you’ll soon discover.
This book distills more than three years of effort to create a modern, cross-platform toolkit as an easy
to understand, organized progression of ideas. The examples contained within this book are simple
enough to be understood without the need for a fancy IDE or compiler, yet they retain the complexity
required to be applicable to problems faced by real applications. Better, the following chapters don’t
focus on a single platform but take a holistic approach to understanding mobile development for all
platforms, not just iOS or Android or Windows.
We wanted to avoid the pitfalls commonly associated with cross-platform toolkits: either they have an
alien-feeling user experience, or they are limited to the lowest common denominator across all the tar-
get platforms. The pattern we fell in love with was to use native APIs, as is the traditional Xamarin way.
Xamarin.Forms offers the user the smallest usable subset of APIs that are required to write the majority
of an app in a unified codebase, and then gives access to the underlying toolkit for fit and finish. The
end result is that the user has the ability to express the majority of their app in unified code, without
losing the flexibility of per-platform implementation.
It works, too, by removing the need to provide every feature inside the abstraction. Instead, we allow
simple access down to the toolkit so that application developers are able to bring out those platform-
specific features that make their app shine. Ninety percent of what makes your app work is the same as
for every other app out there, but working across platforms shouldn’t force you to give up the 10 per-
cent that makes your app unique.
Because of this, Xamarin.Forms is in many ways the “untoolkit,” a toolkit that isn’t so much a toolkit as
it is a way to look at mobile development and use it as a pattern to create mobile apps. If the authors
of Xamarin.Forms can offer you anything to retain as you read this book, it is that toolkits, platforms,
and technologies change very rapidly, but patterns, especially good patterns, rarely die.
When I read the preview editions of this book, I was blown away. Charles understood what we were
trying to do better than anyone else ever had. This book is written knowing that Xamarin.Forms is
about the pattern of creating mobile apps. I believe that by the time you finish reading, you too will
understand what it is we set out to create.
Xamarin.Forms cocreator,
Jason Smith
Introduction
This is the third version of a book about writing applications with Xamarin.Forms, the exciting mobile
development platform for iOS, Android, and Windows unveiled by Xamarin in May 2014. (The first two
versions of this book were Preview Editions.) Xamarin.Forms lets you write shared user-interface code
in C# and XAML (the Extensible Application Markup Language) that maps to native controls on these
platforms.
The Windows support of Xamarin.Forms includes the Windows Runtime (WinRT) for targeting
Windows 8.1 and Windows Phone 8.1 devices, and the Universal Windows Platform (UWP), which is a
form of the Windows Runtime that targets Windows 10 and Windows 10 Mobile devices with a single
program.
The two previous versions of this book were called Preview Editions because they were not com-
plete. At 1200 pages, this is the first edition that can claim to be complete, even though several topics
are not included and Xamarin.Forms continues to be progressively enhanced with no sign of slowing
down.
All information about this book can be found on the book’s home page at:
Who should read this book
This book is for C# programmers who want to write applications using a single code base that targets
the three most popular mobile platforms: iOS, Android, and Windows, encompassing the Universal
Windows Platform and Windows Phone.
Xamarin.Forms also has applicability for those programmers who eventually want to use C# and the
Xamarin.iOS and Xamarin.Android libraries to target the native application programming interfaces
(APIs) of these platforms. Xamarin.Forms can be a big help in getting programmers started with these
platforms or in constructing a prototype or proof-of-concept application.
This book assumes that you know C# and are familiar with the use of the .NET Framework. How-
ever, when I discuss some C# and .NET features that might be somewhat exotic or unfamiliar to recent
C# programmers, I adopt a somewhat slower pace.
Introduction
xvii
Conventions and features in this book
This book has just a few typographical conventions: